//
//  LyTool.m
//  LO_MUSIC
//
//  Created by lanou3g on 16/2/27.
//  Copyright © 2016年 杨少锋. All rights reserved.
//

#import "LyTool.h"

static LyTool *lytool = nil;
@implementation LyTool

//单例
+(instancetype)shareLyTool{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        lytool = [[LyTool alloc]init];
    });
    return lytool;
}

//初始化歌词
-(void)lyerWithStr:(NSString *)str{

    //如果存放模型的数组中有数据,全部移除掉
    if (self.modelArr.count) {
        [self.modelArr removeAllObjects];
    }
    //根据/n切割歌词,结果@[时间 歌词]
    if (str.length < 1) {
        return;
    }
    NSArray *lyArr = [str componentsSeparatedByString:@"\n"];
    for (NSString *singleStr in lyArr) {
        if (!singleStr.length ) {
            continue;
        }
        NSArray *arr = [singleStr componentsSeparatedByString:@"]"];
        //1.第一个元素 时间 第二个元素 歌词
        NSString *time = nil;
        if ([(NSString *)arr.firstObject length]) {
            time =[(NSString *) arr.firstObject substringFromIndex:1];
        }
        NSString *ly =nil;
        if (![(NSString *)arr.lastObject length]) {
            continue;
        }
        ly = arr.lastObject;
        //创建歌词对象
        LyTool*tool = [[LyTool alloc]init];
        tool.ly = ly;
        tool.time = [self timeFromWithStr:time];
        //添加到数组中
        [self.modelArr addObject:tool];
    }
}

-(NSInteger)indexForTime:(float)time{
    int i = 0;
    for (LyTool *tool in self.modelArr) {
        if (tool.time > time) {
            break;
        }
        i++;
    }
    return i - 1 ;
}

-(float)timeFromWithStr:(NSString *)str{
    NSArray *arr = [str componentsSeparatedByString:@":"];
    float time = [arr.firstObject integerValue] * 60.0 + [arr.lastObject floatValue];
    return time;
}

-(NSMutableArray *)modelArr{
    if (!_modelArr) {
        _modelArr = [NSMutableArray array];
    }
    return _modelArr;
}


@end
